package com.chanjiedata.changbs.module.createcard;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.base.BaseActivity;
import com.chanjiedata.changbs.net.Apis;
import com.chanjiedata.changbs.net.NetworkManager;
import com.chanjiedata.changbs.net.interfaces.OnRequestCallBack;
import com.chanjiedata.changbs.proto.Merchantservice;
import com.chanjiedata.changbs.utlis.GsonUtils;
import com.chanjiedata.changbs.utlis.StatusBarUtil;
import com.fm.unionpaysdk.UnionpayTag;
import com.google.protobuf.InvalidProtocolBufferException;
import butterknife.BindView;
import butterknife.ButterKnife;

public class CreateCardActivity extends BaseActivity {

    @BindView(R.id.back_tv)
    TextView backTv;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_shop_message)
    TextView tvShopMessage;
    @BindView(R.id.tv_shop_no)
    TextView tvShopNo;
    @BindView(R.id.btn_start)
    Button btnStart;
    private UnionpayTag mUnionpayTag;
    private Merchantservice.shop item;
    private String tagID = "";
    private String snCode = "";
    private String shopStatus = "0";  // 默认为0
    private String shopTag = "";
    private String ShopUUid = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_creat_first);
        StatusBarUtil.setStatusBarLightMode(this, Color.parseColor("#ffffff"), true);
        ButterKnife.bind(this);
        initView();
        initListener();
        initNFC();
    }

    private void initNFC() {
        // 初始化
        mUnionpayTag = new UnionpayTag();
        mUnionpayTag.initNFC(this);
    }

    private void initView() {
        item = GsonUtils.deSerializedFromJson(getIntent().getStringExtra("data"), Merchantservice.shop.class);
        snCode = getIntent().getStringExtra("snCode");
        shopStatus = item.getStatus();
        shopTag = item.getTag();
        ShopUUid = item.getUuid();
        tvTitle.setText("制卡");
        tvShopName.setText(item.getShopName());
        tvLocation.setText(item.getProvinceName() + " " + item.getCityName() + " " + item.getCountyName());
        tvShopMessage.setText(item.getMccName() + " " + item.getSubName());
        tvShopNo.setText(getIntent().getStringExtra("snCode"));
    }

    private void initListener() {
        backTv.setOnClickListener(v -> finish());
        btnStart.setOnClickListener(v -> {
            // 1.读取卡片
            tagID = mUnionpayTag.getTagId();
            Log.e("tagID", "initListener: "+tagID);
            // 2.判断是否读取成功
            if (tagID.length() > 3)  // 超过3位视为读取成功
            {
                // 3.判断商户的状态
                switch (shopStatus) {
                    case "0":
                        applyShop();
                        break;
                    case "1":
                        // 判断卡片与申请是否一致
                        if (tagID.equals(ShopUUid)) {
                            startWriteCard(item.getTag());
                        } else {
                            showToast("读取卡片与申请卡片不一致");
                        }
                        break;
                    case "2":
                        showToast("商铺已经制卡");
                        break;
                    default:
                        showToast("未知错误");
                }
            } else {
                // 判断错误
                checkStatue(tagID);
                tagID = "";
            }
        });
    }

    private void applyShop() {
        showProgress();
        Merchantservice.apply_shop.Builder builder = Merchantservice.apply_shop.newBuilder();
        builder.setShopCode(item.getShopCode()).setUuid(tagID).setMerchantId(item.getMerchantId())
                .setSnCode(snCode);
        NetworkManager.INSTANCE.post(Apis.apply_shop, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                Merchantservice.apply_shop apply_shop = Merchantservice.apply_shop.parseFrom(response);
                if (!apply_shop.getTag().isEmpty()) {
                    shopStatus = "1"; // 变为已经为制卡功能
                    shopTag = apply_shop.getTag();
                    ShopUUid = tagID;
                    startWriteCard(shopTag);
                }
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                hideProgress();
                showToast(errorMessage);
            }
        });
    }

    private void startWriteCard(String tag) {
        String result = mUnionpayTag.writeDataToTag(tag);
        checkStatue(result);
    }


    private void checkStatue(String value) {

        switch (value) {
            case "100":
                Merchantservice.apply_shop.Builder builder = Merchantservice.apply_shop.newBuilder();
                builder.setShopCode(item.getShopCode()).setUuid(tagID).setMerchantId(item.getMerchantId());
                Log.e("mango", "checkStatue: "+item.getShopCode() + " " + tagID );
                NetworkManager.INSTANCE.post(Apis.card_write, builder.build().toByteArray(), new OnRequestCallBack() {
                    @Override
                    public void onOk(byte[] response) {
                        hideProgress();
                    }

                    @Override
                    public void onError(int errorCode, String errorMessage) {
                    }
                });
                Intent intent = new Intent(this, CreateSucceedActivity.class);
                startActivity(intent);
                finish();
                break;
            case "101":
                Toast.makeText(this, "该卡片已制作过，请换卡尝试", Toast.LENGTH_SHORT).show();
                break;
            case "102":
                Toast.makeText(this, "卡片不是NDEF格式的卡片", Toast.LENGTH_SHORT).show();
                break;
            case "103":
                Toast.makeText(this, "写入卡片数据超过卡片可写入最大值", Toast.LENGTH_SHORT).show();
                break;
            case "104":
                Toast.makeText(this, "手机不支持nfc功能 或手机未打开nfc", Toast.LENGTH_SHORT).show();
                break;
            case "105":
                Toast.makeText(this, "卡片写入失败,请将卡片保持与手机背部NFC感应区贴合直至制卡成功", Toast.LENGTH_SHORT).show();
                break;
            case "106":
                Toast.makeText(this, "卡片设置只读模式失败", Toast.LENGTH_SHORT).show();
                break;
            case "107":
            default:
                Toast.makeText(this, "未知错误", Toast.LENGTH_SHORT).show();
                break;
        }
    }

}
